<template>
    <div class="wh-100% flex flex-col">
        <div class="w-full box-border py-2.5 flex justify-between items-center">
            <n-button text :focusable="false">
                <n-select
                    class="w-35"
                    v-model:value="module"
                    :options="selectOptions"
                    :render-label="renderOptionLabel"
                ></n-select>
            </n-button>
            <view class="font-size-5 font-bold">
                {{ new Date(timestamp).toLocaleDateString() }}
            </view>
            <div class="flex gap-2.5">
                <n-button secondary @click="handleReload">
                    <template #icon>
                        <ReloadCircle />
                    </template>
                </n-button>
                <n-button
                    secondary
                    type="primary"
                    :focusable="false"
                    @click="handleDownloadFile"
                >
                    <template #icon>
                        <ArrowDownCircle />
                    </template>
                </n-button>
                <n-button
                    secondary
                    type="error"
                    :focusable="false"
                    @click="handleDeletePrediction"
                >
                    <template #icon>
                        <TrashBin />
                    </template>
                </n-button>
            </div>
        </div>
        <div class="flex-1 overflow-scroll">
            <WeatherChart
                ref="wChartRef"
                v-if="module === 'weather'"
                :timestamp="timestamp"
            />
            <StockChart
                ref="sChartRef"
                v-if="module === 'stock'"
                :timestamp="timestamp"
            />
            <ElectricityChart
                ref="eChartRef"
                v-if="module === 'electricity'"
                :timestamp="timestamp"
            />
        </div>
        <div class="w-full">
            <TimeSelect
                :timestamp="timestamp"
                @update:timestamp="handleChangeDate"
            />
        </div>
    </div>
</template>

<script lang="ts" setup>
import { h, ref, onMounted, computed, Component } from "vue";
import { NIcon, SelectOption } from "naive-ui";
import { TrashBin, ArrowDownCircle, ReloadCircle } from "@vicons/ionicons5";

import SvgIcon from "@/components/svg-icon/index.vue";
import WeatherIcon from "@/assets/icon/weather.svg";
import StockIcon from "@/assets/icon/stock.svg";
import ElectricityIcon from "@/assets/icon/electricity.svg";

import TimeSelect from "./components/time-select/index.vue";
import WeatherChart from "./components/weather-chart/index.vue";
import StockChart from "./components/stock-chart/index.vue";
import ElectricityChart from "./components/electricity-chart/index.vue";

import {
    saveModulePredictionToLocal,
    deleteModulePrediction,
} from "@/service/api/predict";

const selectOptions: SelectOption[] = [
    {
        label: "天气预测",
        value: "weather",
        icon: () => h(SvgIcon, { icon: WeatherIcon }),
    },
    {
        label: "股票预测",
        value: "stock",
        icon: () => h(SvgIcon, { icon: StockIcon }),
    },
    {
        label: "电力预测",
        value: "electricity",
        icon: () => h(SvgIcon, { icon: ElectricityIcon }),
    },
];

const renderOptionLabel = (option: SelectOption) => {
    return h(
        "div",
        {
            class: ["flex", "items-center"],
        },
        [
            h(
                "div",
                {
                    class: ["wh-16px", "rounded-full", "bg-#F1F1F1", "mr-2.5"],
                },
                [
                    h(NIcon, {
                        size: 16,
                        component: option.icon as Component,
                    }),
                ]
            ),
            option.label as string,
        ]
    );
};

const timestamp = ref(new Date(new Date().toLocaleDateString()).getTime());

const wChartRef = ref<InstanceType<typeof WeatherChart> | null>(null);
const sChartRef = ref<InstanceType<typeof StockChart> | null>(null);
const eChartRef = ref<InstanceType<typeof ElectricityChart> | null>(null);

const chartRefMap = {
    weather: wChartRef,
    stock: sChartRef,
    electricity: eChartRef,
};

// 当前预测模型
const module = ref<"weather" | "stock" | "electricity">("weather");

const handleChangeDate = (value: number) => {
    timestamp.value = value;
};

const handleReload = async () => {
    await chartRefMap[module.value].value?.handleReload();
};

const handleDownloadFile = async () => {
    const data: any = chartRefMap[module.value].value?.getCurrentData();
    if (!data) {
        window.NMessage.warning("暂无数据");
        return;
    }
    try {
        saveModulePredictionToLocal(data);
        window.NMessage.success("下载成功");
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
};

const handleDeletePrediction = () => {
    if (
        timestamp.value === new Date(new Date().toLocaleDateString()).getTime()
    ) {
        window.NMessage.error("无法删除今日数据");
        return;
    }

    if (!chartRefMap[module.value].value?.getCurrentData()) {
        window.NMessage.warning("暂无数据");
        return;
    }

    window.NDialog.warning({
        title: "警告",
        content: "是否删除该日预测数据",
        closable: false,
        positiveText: "确认",
        negativeText: "取消",
        onPositiveClick: async () => {
            const date = new Date(timestamp.value).toLocaleDateString("sv-SE", {
                timeZone: "Asia/Shanghai",
            });
            const key = `${module.value}:${date}`;
            try {
                await deleteModulePrediction(key);
                window.NMessage.success("删除成功");

                chartRefMap[module.value].value?.handleReload();
            } catch (err) {
                window.NMessage.error((err as Error).message);
            }
        },
    });
};
</script>

<style scoped></style>
